<template>
  <div class="center">
    <!-- 表单 -->
    <!-- <table-page
      :formData="formData"
      :tableData="tableData"
    >
      <template #input-button="{ row }">
        <el-input v-model="row.value" :placeholder="row.placeholder" class="input-with-select game_select">
          <el-button type="primary" slot="append" icon="el-icon-search" @click="getQry" />
        </el-input>
      </template>
    </table-page> -->
    <el-row class="row-b10">
      <el-col :lg="6" :sm="12" :xs="12">
        <el-input v-model="startTerm" placeholder="开始期号"/>
      </el-col>
      <el-col :lg="6" :sm="12" :xs="12">
        <el-input v-model="endTerm" placeholder="结束期号"/>
      </el-col>
      <el-col :lg="6" :sm="12" :xs="12">
        <el-select
          class="_sel"
          v-model="gameNo"
          placeholder="请选择游戏"
          style="width: 100%"
        >
          <el-option label="排列五" value="350133" />
          <el-option label="七星彩" value="04" />
          <el-option label="大乐透" value="85" />
        </el-select>
      </el-col>
      <el-col :lg="6" :sm="12" :xs="12">
        <el-input v-model="pageSize" placeholder="请输入数量" class="input-with-select game_select">
          <el-button type="primary" slot="append" icon="el-icon-search" @click="getQry" />
        </el-input>
      </el-col>
    </el-row>
    <!-- 搜索和搜索历史记录 -->
    <el-row>
      <el-col :span="24" class="mb20">
        <ul class="ul">
          <li v-for="(item,index) in searchLog" :key="index" class="li">
            <span @click="queryNum(item);searchVal = item">{{ item }}</span>
            <i class="el-icon-circle-close" @click.stop="removeLog(index)"></i>
          </li>
        </ul>
      </el-col>
    </el-row>
    <!-- 随机数 -->
    <el-row>
      <el-col :span="3" v-for="(dom,key) in domlist" :key="key">
        <el-button
          :loading="dom.loading"
          icon="el-icon-refresh"
          type="primary"
          size="mini"
          class="radio0"
          style="width: 100%;padding: 7px 0;"
          @click="onRandom(totalNum,dom)"
        />
        <input
          type="text"
          v-model="dom.cur"
          ref="int"
          class="radio0 inp"
          :id="'inp'+key"
          :placeholder="dom.placeholder"
          @keydown="onNext($event, dom.cur, key)"
        >
        <div class="col">
          <span v-for="(item, index) in dom.arr" :key="index">{{ item }}</span>
        </div>
      </el-col>
      <el-col :span="3">
        <el-button
          type="danger"
          size="mini"
          class="radio0"
          style="width: 100%;padding: 7px 0;"
          @click="onSum"
        >计算</el-button>
        <el-input v-model="totalNum" class="radio0" placeholder="条数" />
      </el-col>
    </el-row>
    <!-- 表格 -->
    <div style="margin-top: 20px;">
      <el-table
        :data="code"
        :header-cell-style="{'text-align': 'center','padding': '5px 0'}"
        :cell-style="{'text-align':'center','padding': '5px 0'}"
        style="width: 100%">
        <el-table-column
          prop="lotteryDrawNum"
          label="期号">
        </el-table-column>
        <el-table-column>
          <template slot="header">
            <el-input v-model="searchVal" size="mini" placeholder="输入号码,号码后面加“s”表示不缓存">
              <el-button slot="append" size="mini" icon="el-icon-search" @click="queryNum(searchVal)"/>
            </el-input>
          </template>
          <el-table-column
            label="开奖号码">
            <template slot-scope="scope">
              <div v-html="scope.row.num"></div>
            </template>
          </el-table-column>
          <el-table-column
            prop="lotteryDrawTime"
            label="开奖日期">
          </el-table-column>
        </el-table-column>
        <el-table-column
          prop="drawPdfUrl"
          label="开奖公告">
          <template slot-scope="scope">
            <div style="color: dodgerblue;cursor: pointer;" @click="handleView(scope.row)">查看</div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 100, 200, 500, 1000]"
        :page-size="pageSize"
        layout="sizes"
        :total="pageTotal"
        style="text-align: center;margin-top: 15px;"/>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
// import tablePage from './common/tablePage'
export default {
  components: {
    // tablePage
  },
  data() {
    return {
      searchVal: '',
      startTerm: '',
      endTerm: '',
      domlist: [{
        loading: false,
        maxnum: 9,
        cur: null,
        arr: [],
        show: true,
        placeholder: '0~9'
      }, {
        loading: false,
        maxnum: 9,
        cur: null,
        arr: [],
        show: true,
        placeholder: '0~9'
      }, {
        loading: false,
        maxnum: 9,
        cur: null,
        arr: [],
        show: true,
        placeholder: '0~9'
      }, {
        loading: false,
        maxnum: 9,
        cur: null,
        arr: [],
        show: true,
        placeholder: '0~9'
      }, {
        loading: false,
        maxnum: 9,
        cur: null,
        arr: [],
        show: true,
        placeholder: '0~9'
      }, {
        loading: false,
        maxnum: 9,
        cur: null,
        arr: [],
        show: true,
        placeholder: '0~9'
      }, {
        loading: false,
        maxnum: 14,
        cur: null,
        arr: [],
        show: true,
        placeholder: '0~14'
      }],
      code: [],
      gameNo: '04',
      totalNum: 2,
      logNum: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      pagerCount: 3,
      pageTotal: 0,
      randomNumStr: [],
      formData: [
        {
          el: 'el-input',
          value: '',
          prop: 'startTerm',
          label: '开始期号',
          placeholder: '请输入开始期号',
          defaultValue: ''
        },
        {
          el: 'el-input',
          value: '',
          prop: 'endTerm',
          label: '结束期号',
          placeholder: '请输入结束期号',
          defaultValue: ''
        },
        {
          el: 'el-select',
          value: '04',
          prop: 'gameNo',
          label: '请选择游戏',
          placeholder: '请选择游戏',
          width: '100%',
          defaultValue: '04',
          subItems: [
            {
              el: 'el-option',
              label: '排列五',
              value: '350133'
            },
            {
              el: 'el-option',
              label: '七星彩',
              value: '04'
            },
            {
              el: 'el-option',
              label: '大乐透',
              value: '85'
            }
          ]
        },
        {
          type: 'slot',
          prop: 'pageSize',
          value: 10,
          slotName: 'input-button',
          placeholder: '输入数量',
          defaultValue: 10
        }
      ],
      tableData: [],

      // 求前100的数
      odl:[
        {str: 0, num: 0},
        {str: 1, num: 0},
        {str: 2, num: 0},
        {str: 3, num: 0},
        {str: 4, num: 0},
        {str: 5, num: 0},
        {str: 6, num: 0},
        {str: 7, num: 0},
        {str: 8, num: 0},
        {str: 9, num: 0}
      ],
      odlNew: [
        {str: 0, num: 0},
        {str: 1, num: 0},
        {str: 2, num: 0},
        {str: 3, num: 0},
        {str: 4, num: 0},
        {str: 5, num: 0},
        {str: 6, num: 0},
        {str: 7, num: 0},
        {str: 8, num: 0},
        {str: 9, num: 0},
        {str: 10, num: 0},
        {str: 11, num: 0},
        {str: 12, num: 0},
        {str: 13, num: 0},
        {str: 14, num: 0}
      ],
      
      pageNum: 10,
      randomArr: []
    }
  },
  mounted() {
    // console.log(this.id,123)
    this.getQry()
    if (localStorage.getItem('log')) {
      this.logNum = [...new Set(JSON.parse(localStorage.getItem('log')))]
    }
  },
  computed: {
    searchLog() {
      return [...this.logNum,...this.randomNumStr].filter(item => item !== 's')
    }
  },
  methods: {
    // 随机数字转字符串
    onSum() {
      let sumArr = []
      for (let i = 0; i < this.totalNum; i++) {
        sumArr.push(`${this.domlist[0].arr[i]??''}${this.domlist[1].arr[i]??''}${this.domlist[2].arr[i]??''}${this.domlist[3].arr[i]??''}${this.domlist[4].arr[i]??''}${this.domlist[5].arr[i]??''}${this.domlist[6].arr[i]??''}s`)
      }
      this.randomNumStr = sumArr
    },
    // 查看
    handleView(row) {
      const newWindow = window.open('about:blank', '_blank')
      // 设置新窗口标题
      newWindow.document.title = '正在跳转...'
      newWindow.document.write('加载中...')
      try {
        // 异步请求返回后填充 URL
        newWindow.location.href = row.drawPdfUrl
        newWindow.focus()
      } catch (error) {
        newWindow.close()
        alert('打开新窗口失败')
      }

    },
    onNext(e,val,i) {
      if (e.keyCode == 8) {
        if (!val) {
          this.$nextTick(() => {
            this.$refs.int[i-1].focus()
          })
        } else if (val) {
          this.$nextTick(() => {
            this.$refs.int[i].focus()
          })
        } else if (i == 0) {
          this.$nextTick(() => {
            this.$refs.int[i].focus()
          })
        }
      } else {
        let reg = /\d/
        if (val) {
          if (reg.test(val)) {
            if (i >= 6) {
              this.$nextTick(() => {
                this.$refs.int[i].focus()
              })
            } else if (i < 6) {
              this.$nextTick(() => {
                this.$refs.int[i+1].focus()
              })
            }
          } else {
            this.$message.error('只能输入数字！')
          }
        }
      }
    },
    // 查询号码
    getQry () {
      for (let i = 0; i < this.formData.length; i++) {
        // console.log(this.formData[i].value);
      }
      if (isNaN(this.pageSize)) {
        this.$message.error('只能输入数字！')
      } else {
        axios.get(`https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=${this.gameNo}&provinceId=0&pageSize=${this.pageSize}&isVerify=1&pageNo=${this.currentPage}&startTerm=${this.startTerm}&endTerm=${this.endTerm}`).then(res => {
          if (res.data.success) {
            this.code = res.data.value.list
            this.pageTotal = res.data.value.total
            for (let i = 0; i < this.code.length; i++) {
              if (this.code[i].lotteryDrawResult) {
                this.code[i].num = this.code[i].lotteryDrawResult.replaceAll(' ','')
              }
            }
          }
        })
      }
    },
    // 当前页
    handleCurrentChange(e) {
      this.currentPage = e
      this.getQry()
    },
    // 页数总数
    handleSizeChange(e) {
      this.pageSize = e
      this.getQry()
    },
    // 随机数
    onRandom(index, item) {
      if (!item.cur) {
        this.$message({
          showClose: true,
          message: '不能为空！',
          type: 'warning'
        })
        return false
      } else if (isNaN(item.cur)) {
        this.$message({
          showClose: true,
          message: '只能输入数字！',
          type: 'warning'
        })
        return false
      } else if (item.maxnum == 14 && item.cur > 14) {
        this.$message({
          showClose: true,
          message: '不能大于14！',
          type: 'warning'
        })
        return false
      } else if (item.maxnum != 14 && item.cur > 9) {
        this.$message({
          message: '不能大于9！',
          type: 'warning'
        })
        return false
      }
      item.loading = true
      item.arr = []
      var teim1 = setInterval(() => {
        var num = Math.trunc(Math.random() * (item.maxnum+1))
        if (num === Number(item.cur)) {
          item.arr = item.arr.concat(Math.trunc(Math.random() * (item.maxnum+1)))
        }
        if (item.arr.length >= index) {
          item.loading = false
          clearInterval(teim1)
        }
      }, 100)
    },
    // 查询中了几个
    queryNum(inp) {
      let isReg = /^\d{5,9}[s]?$/i
      if (this.code.length == 0) {
        this.$message.error('请选择游戏！')
        return false;
      }
      if (!isReg.test(inp)) {
        this.$message.error('5到9的数字！')
        return false;
      }
      // 缓存本地
      if (!/[s]/ig.test(inp)) {
        // console.log('hove S')
        this.logNum.push(inp)
        this.logNum = [...new Set(this.logNum)]
        localStorage.setItem('log',JSON.stringify(this.logNum))
      }
      let inpLen;
      let reg;
      let res;
      if (inp.length >= 8 ) {
        inpLen = inp.substr(0,5).split('')
        inpLen[5] = inp[inp.length - 3]
        inpLen[6] = inp[inp.length - 2] + '' + inp[inp.length - 1]
      } else {
        inpLen = inp.split('')
      }
      for (let i = 0; i < this.code.length; i++) {
        this.code[i].num = this.code[i].lotteryDrawResult
        res = this.code[i].num.split(' ')
        this.allGet(inpLen,res)
        for (let j = 0; j < inpLen.length; j++) {
          if (inpLen[j] == res[j]) {
            reg = new RegExp(inpLen[j])
            res[j] = res[j].replace(reg, `<span style="color: red">${inpLen[j]}</span>`)
          }
        }
        this.code[i].num = res.join('')
      }
    },
    // 删除历史记录
    removeLog(index) {
      this.logNum.splice(index,1)
      localStorage.setItem('log',JSON.stringify(this.logNum))
    },
    // 全中
    allGet(a,b) {
      if (a.join('').indexOf(b.join('')) >= 0) {
        this.$alert(b.join(''), '恭喜您中头奖了！', {
          confirmButtonText: '确定'
        });
      }
    }
  },
  watch: {
    code: {
      handler(e) {
        if (e.length > 0) {
          let data_ = e[1].num.split('')
          for (let i = 0; i < this.domlist.length; i++) {
            this.domlist[i].cur = data_[i]
          }
          if (data_.length == 8) {
            this.domlist[6].cur = `${data_[data_.length - 2]}${data_[data_.length - 1]}`
          }
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.center{
  max-width: 1200px;
  width: 100%;
  margin: 20px auto 0;
}
.col {
  display: flex;
  flex-direction: column;
  text-align: center;
  align-items: center;
  span {
    display: flex;
    // width: 30px;
    // height: 30px;
    border-radius: 15px;
    // background: #f00;
    // margin: 10px 0;
    // line-height: 30px;
    margin-top: 10px;
    color: #f00;
    justify-content: center;
    align-items: center;
  }
}
.el-row {
  justify-content: center;
  .el-col {
    padding: 0 5px;
    &:nth-child(7) {
      span {
        // background: #00f;
        color: #00f;
      }
    }
  }
}
.border-lr{
  padding: 0 5px;
  border-left: 1px solid red;
  border-right: 1px solid red;
  margin-right: 5px;
}
/deep/.radio0{
  border-radius: 0;
  .el-input__inner{
    border-radius: 0;
    height: 35px;
    line-height: 30px;
    text-align: center;
    padding: 0;
  }
  &.inp{
    .el-input__inner{
      border-top: 0;
      border-right: 0;
      border-left: 0;
      border-bottom: 1px solid rgb(0, 157, 255);
      padding: 0;
      background: transparent;
      width: 100%;
    }
  }
  &.inp{
    border-top: 0;
    border-right: 0;
    border-left: 0;
    border-bottom: 1px solid rgb(0, 157, 255);
    padding: 0;
    background: transparent;
    width: 100%;
    text-align: center;
    height: 35px;
    outline: none;
    font-size: 15px;
  }
}
.ul{
  padding: 0;
  margin: 0;
  .li{
    list-style-type: none;
    display: inline-block;
    margin-right: 12px;
    padding: 10px 0;
    color: #666;
    letter-spacing: .5px;
    font-size: 14px;
    i{
      margin-left: 7px;
      color: #F56C6C;
      cursor: pointer;
      -webkit-tap-highlight-color:transparent
    }
    span{
      cursor: pointer;
      -webkit-tap-highlight-color:transparent
    }
  }
}
/deep/.game_select{
  .el-input-group__prepend{
    width: 125px;
    padding: 0;
    .el-select{
      margin: -1px;
    }
  }
}
</style>